<template>
  <n-spin :show="loading" class="lt-wrapper">
    <n-form>
      <n-form-item label="用户名">
        <n-input v-model:value="loginForm.username"></n-input>
      </n-form-item>
      <n-form-item label="密码">
        <n-input v-model:value="loginForm.password"></n-input>
      </n-form-item>
    </n-form>

    <n-button @click="submitSignUp"> 登录 </n-button>
  </n-spin>
</template>

<script>
import serverApi from '/src/api/fsync/server.js'
import globalStore from '/src/components/pinia/store.js'
import base64Tool from '/src/utils/encrypt/base64-tool.js'

export default {
  setup() {
    const store = globalStore()

    return {
      store
    }
  },
  inject: [ 'Message' ],
  data () {
    return {
      loading: true,
      loginForm: {
        username: '',
        password: '',
        // rememberMe: false,
      }
    }
  },
  created(){
    this.check()
  },
  methods: {
    check() {
      this.loading = true
      serverApi.checkLogin()
      .then(res => {
        this.loading = false
        this.store.setToken(res.data)
        this.store.setHasAccount(false)
        this.afterLogin()
      }, err => {
        this.loading = false
        console.error(err)
      })
    },

    submitSignUp() {
      let data = {
        username: base64Tool.encodeReqData(this.loginForm.username),
        password: base64Tool.encodeReqData(this.loginForm.password)
      }

      serverApi.login(data)
      .then(res => {
        this.store.setToken(res.data)
        this.afterLogin()
        this.store.setHasAccount(true)
        this.Message.success( "登录成功", { closable: true, duration: 3000 } )
      }, err => {
        this.Message.error( err.message, { closable: true, duration: 3000 } )
      })
    },

    afterLogin() {
      let from = this.$route.query.from
        // from = from ? from : window.location.origin + '/home'
        from = from ? from : '/home'
        if(from) {
          // this.$router.push({ path: from})
          this.$router.push(from)
          // window.location.href = from
        }
    },

  }
}
</script>

<style scoped>
.lt-wrapper {
  margin: 3rem auto 4rem auto;
  width: 60rem;
  text-align: left;
}
</style>
